/* js for the workweek page */
$(document).ready(function(){
	Workweek.init();
});
WEvent = {
	id:"",name:"",duration:"",day:"",start_time:"",category:"",
	set:function(id,name,duration,day,start_time,category){
		WEvent.id = id;
		WEvent.name = name;
		WEvent.duration = duration;
		WEvent.day = day;
		WEvent.start_time = start_time || "";
		WEvent.category = category;
	},
	setEmpty:function(){
		WEvent.id = "";
		WEvent.name = "";
		WEvent.duration = "";
		WEvent.day = "";
		WEvent.start_time = "";
		WEvent.category = "";
	},
	get:function(){
		var result = {
			id:WEvent.id,
			name:WEvent.name,
			duration:WEvent.duration,
			day:WEvent.day,
			start_time:WEvent.start_time,
			category:WEvent.category
		};
		return result;
	}
};
Workweek = {
	mouseX:0,
	mouseY:0,
	cloneX:0,
	cloneY:0,
	$clone:$(),
	init:function(){
		// calculate capacity for all days
		$('.weekday[day]').each(function(){
			Workweek.calculateCapacity($(this).attr('day'));
		});
		$('.workweek-event.unscheduled').on('mousedown',function(e){
			// ignore if the x is being clicked
			if($(e.target).hasClass('delete-workweek')){
				return;
			}
			// right click does nothing
			if(e.which != 1){return;}
			Workweek.copyUnscheduledEvent(this,e);
			e.preventDefault();
			Touch.freeze();
		});
		$(document).on('mouseup',function(){
			Touch.unfreeze();
			if(Workweek.$clone.length == 0){return;}
			Workweek.mouseX = 0;
			Workweek.mouseY = 0;
			if($('.eligible').length > 0){
				Workweek.scheduleUnscheduledEvent();
			}
			WEvent.setEmpty();
			Workweek.destroyClones();
			// remove dimming
			$('.weekday').css({opacity:1});
		});
		$(document).on('mousemove',function(e){
			Workweek.handleUnscheduledMouseMove(e);
		});
		
		// drag resize
		var Resize = {};
		$('[day]').delegate('.drag-resize','mousedown.resize',function(e){
			// right click does nothing
			if(e.which != 1){return;}
			Touch.freeze();
			// calculate the current mouse position
			Resize.mouseY = e.pageY;
			// gather the max size of this element
			Resize.$event = $(this).closest('.scheduled-event');
			// make sure its not saving
			if(Resize.$event.hasClass('saving')){return;}
			Resize.$timeblock = Resize.$event.parent();
			var $nextAll = Resize.$timeblock.nextAll('.timeblock');
			Resize.size = +Resize.$event.attr('duration') / 15;
			Resize.calculatedSize = Resize.size;
			var stepsToSkip = Resize.size-1;
			Resize.maxSize = Resize.size;
			$nextAll.each(function(){
				if(stepsToSkip > 0){
					stepsToSkip--;
				} else {
					// highlight time text
					if(stepsToSkip == 0){
						$(this).addClass('eligible-time');
						stepsToSkip--;
					}
					if($(this).hasClass('workweek-event')){
						return false;
					}
					Resize.maxSize++;
				}
				$(this).addClass('eligible');
			});
			// show and reposition the duration text
			Resize.$duration = Resize.$event.find('.scheduled-event-duration');
			Resize.$duration.show();
			// hide the resize bar
			Resize.$event.find('.drag-resize').hide();
			// highlight time text
			Resize.$timeblock.addClass('eligible-time');
			
			// bind the mouse move
			$(document).unbind('mousemove.resizeEvent').bind('mousemove.resizeEvent',function(e){
				var diff = e.pageY - Resize.mouseY;
				var step = (diff - (diff % 15)) / 15;
				var calculatedStep = Resize.size + step;
				var duration = (calculatedStep * 15);
				var calculatedHeight = duration - 1;
				if(calculatedStep >= 1 && calculatedStep <= Resize.maxSize){
					Resize.$event.css({height:calculatedHeight+'px'});
					Resize.calculatedSize = calculatedStep;
					Resize.$duration.text(Workweek.humanizeDuration(duration));
					// highlihgt time text
					$('.eligible-time:last').removeClass('eligible-time');
					var $next = Resize.$timeblock;
					for(var i = 0; i < calculatedStep; i++){
						$next = $next.next();
					}
					$next.addClass('eligible-time');
				}
				
			});
			// bind the mouseup which concludes the resize
			$(document).unbind('mouseup.resizeEvent').bind('mouseup.resizeEvent',function(){
				Touch.unfreeze();
				$(document).unbind('mouseup.resizeEvent');
				$(document).unbind('mousemove.resizeEvent');
				$('.eligible').removeClass('eligible');
				var id = Resize.$event.attr('workweekEventID');
				var day = Resize.$event.closest('[day]').attr('day');
				var minute = Workweek.quarterToMinute(Resize.$timeblock.attr('quarter'));
				var time = Workweek.getTimeString(Resize.$timeblock.attr('hour'),minute);
				var duration = Resize.calculatedSize * 15;
				Resize.$event.attr('duration',duration);
				Workweek.calculateCapacity(day);
				Workweek.saveEventTime(id,day,duration,time);
				Resize.$duration.hide();
			});
		});
		
		// Drag move
		var Drag = {};
		$('[day]').delegate('.scheduled-event','mousedown.dragEvent',function(e){
			if($(this).hasClass('editing')){return;}
			// if clicking on delete icon, return
			var $target = $(e.target);
			if($target.hasClass('delete-workweek') 
			|| $target.hasClass('workweek-category-picker') 
			|| $target.hasClass('workweek-category-color')
			|| $target.hasClass('edit-event-name')
			){
				return;
			}
			// right click does nothing
			if(e.which != 1){return;}
			if($(this).hasClass('saving') || $(e.target).hasClass('drag-resize')){
				return;
			}
			Touch.freeze();
			// test for and remove old clone
			$('#dragClone').remove();
			// save the old event and old position
			var $event = $(this);
			Drag.$oldEvent = $event.clone();
			Drag.$oldPosition = $event.parent();
			Drag.startX = $event.offset().left;
			Drag.startY = $event.offset().top;
			Drag.mouseX = e.pageX;
			Drag.mouseY = e.pageY;
			Drag.day = Drag.$oldPosition.closest('[day]').attr('day');
			var name = $event.find('.workweek-event-name').text();
			var duration = $event.attr('duration');
			Drag.size = +duration / 15;
			var width = $event.width();
			// remove the event
			$event.remove();
			// recalculate the capacities
			Workweek.calculateCapacity(Drag.day);
			// figure out the category
			Drag.category = Drag.$oldEvent.attr('class');
			var index = Drag.category.indexOf('we-cat');
			Drag.category = Drag.category.charAt(index+6);
			
			// create the clone
			Drag.$clone = Workweek.getEventHTML('dragClone',name,duration,Drag.category);
			Drag.$clone.css({
				top:Drag.startY + 'px',
				left:Drag.startX + 'px',
				position:"absolute",
				width:width+"px",
				height:duration+"px",
				zIndex:99,
				opacity:.7
			});
			// enable duration on the clone
			Drag.$clone.find('.scheduled-event-duration').show();
			// hide the drag bar
			Drag.$clone.find('.drag-resize').hide();
			$('body').append(Drag.$clone);
			// remove the controls
			Drag.$clone.find('.workweek-category-picker,.delete-workweek,.workweek-category-picker-colors').remove();
			Drag.$oldEvent.find('.workweek-category-picker,.delete-workweek,.workweek-category-picker-colors').remove();
			// find maxLeft by window width
			var maxRight = $(window).width() - Drag.$clone.width();
			// bind mousemove
			$(document).unbind('mousemove.dragEvent').bind('mousemove.dragEvent',function(e){
				var deltaX = e.pageX - Drag.mouseX;
				var deltaY = e.pageY - Drag.mouseY;
				var left = Drag.startX + deltaX;
				var top = Drag.startY + deltaY;
				if(left > maxRight){
					left = maxRight;
				}
				Drag.$clone.css({
					left:left+'px',
					top:top+'px'
				});
				var $hover = Workweek.getHover(left,top);
				Workweek.highlightHoverEligible($hover,Drag.size);
			});
			// bind mouseup
			$(document).unbind('mouseup.dragEvent').bind('mouseup.dragEvent',function(){
				Touch.unfreeze();
				$(document).unbind('mouseup.dragEvent');
				$(document).unbind('mousemove.dragEvent');
				// restore the old event if no save
				if($('.eligible').length > 0){
					var $timeblock = $('.eligible:first');
					$timeblock.prepend(Drag.$oldEvent);
					var minute = Workweek.quarterToMinute($timeblock.attr('quarter'));
					var time = Workweek.getTimeString($timeblock.attr('hour'),minute);
					Workweek.saveEventTime(
						Drag.$oldEvent.attr('workweekeventid'),
						$timeblock.closest('[day]').attr('day'),
						Drag.$oldEvent.attr('duration'),
						time
					);
				} else {
					Drag.$oldPosition.prepend(Drag.$oldEvent);
					Workweek.calculateCapacity(Drag.day);
				}
				Drag.$clone.remove();
			});
		});	
		
		// delegate action for .workweek-category-picker
		$('[day]').delegate('.workweek-category-picker','click',function(){
			var $this = $(this).animate({opacity:0},200);
			var $event = $this.closest('.scheduled-event');
			var classes = $event.attr('class');
			var category = classes.charAt(classes.indexOf('we-cat')+6);
			var $picker = $('<div class="workweek-category-picker-colors we-cat'+category+'"></div>');
			var $span = $('<span class="workweek-category-color-description"></span>');
			var $delete = $event.find('.delete-workweek');
			$delete.css({opacity:0});
			$picker.append($span);
			for(var i = 0; i < 7; i++){
				var catClass = "we-cat"+i+'b';
				if(category == i){
					catClass += " current-category";
				}
				var $color = $('<div class="workweek-category-color '+catClass+'" category="'+i+'" name="'+Workweek.categories[i]+'"></div>');
				// mouseenter and mouse leave
				$color.bind('mouseenter',function(){
					var category = $(this).attr('category');
					$span.show();
					$span.text(Workweek.categories[category]);
				})
				$color.bind('mouseleave',function(){
					$span.hide();
				});
				$picker.append($color);
			}
			$event.append($picker);
			$picker.fadeIn();
			
			// click event for changing category
			$picker.find('.workweek-category-color').on('click',function(){
				var newcategory = $(this).attr('category');
				// change event category
				$event.removeClass('we-cat'+category);
				$picker.removeClass('we-cat'+category+'b');
				$event.addClass('we-cat'+newcategory);
				$picker.addClass('we-cat'+newcategory+'b');
				var id = $event.attr('workweekeventid');
				// fireoff save event
				$picker.fadeOut();
				Ajax.run({
					method:"workweekService.saveWorkweekEvent",
					args:{
						workweekEventID:id,
						category:newcategory
					},
					onsuccess:function(){
						Workweek.loadEvent(id);
					}
				});
			});
			
			//auto remove if nothing is done
			setTimeout(function(){
				$this
				$picker.fadeOut(2000,function(){
					$delete.animate({opacity:1},200);
				});
			},7000);
			
		});
		
		// delegate action for editing events
		$('[day]').delegate('.edit-event-name','click',function(){
			var $this = $(this);
			var $event = $this.closest('.scheduled-event');
			// inject here
			Workweek.renderEditControls($event);
		});
	},
	handleUnscheduledMouseMove:function(e){
		if(Workweek.$clone.length == 1){
			var event = WEvent.get();
			var deltaX = e.pageX - Workweek.mouseX;
			var deltaY = e.pageY - Workweek.mouseY;
			var newX = Workweek.cloneX + deltaX;
			var newY = Workweek.cloneY + deltaY;
			Workweek.$clone.css({
				left:newX+"px",
				top:newY+"px"
			});
			var $hover = Workweek.getHover(newX,newY);
			// only allow hover for current day
			if(+$hover.closest('[day]').attr('day') != event.day){
				$('.eligible').removeClass('eligible');
				return;
			}
			var capacity = +$hover.attr('capacity') || "";
			var size = +Workweek.$clone.attr('size');
			// highlight eligible
			Workweek.highlightHoverEligible($hover,size);
		}
	},
	renderEditControls:function($event,isNew){
		var isNew = isNew || false;
		// keep the old event for cancel
		var $oldEvent = $event.clone();
		// strip out all elements
		$event.find('.drag-resize,.workweek-event-name,.delete-workweek').remove();
		// create the input box and controls
		var $cancel = $('<i class="fa fa-reply"></i>');
		var $input = $('<input name="event-name" validate="maxLength200">');
		var $save = $('<i class="fa fa-check"></i>');
		// add editing class to prevent drag
		$event.addClass('editing');
		// change css a bit if 15minute event
		if($event.attr('duration') == '15'){
			$cancel.css({top:"1px"});
			$input.css({height:"13px",top:"-3px"});
			$save.css({top:"0px"});
		}
		// assign cancel to back button
		$cancel.click(function(){
			if(isNew){
				$event.remove();
			} else {
				$event.replaceWith($oldEvent);
			}
		});
		// bind save to icon
		$save.click(function(){
			if($input.val() == ""){
				$input.css({border:"1px solid red"});
				setTimeout(function(){
					$input.css({border:"1px solid #dddddd"});
				},1000);
			} else {
				// paste the old event back with new name for illusion of fast save
				$oldEvent.find('.edit-event-name').text($input.val());
				$event.replaceWith($oldEvent);
				// get the start_time from position of event
				var $timeblock = $oldEvent.closest('.timeblock');
				var hour = $timeblock.attr('hour');
				var minute = (+$timeblock.attr('quarter')-1) * 15;
				var time = Workweek.getTimeString(hour,minute);
				var day = $timeblock.closest('[day]').attr('day');
				// setup the args
				var args = {
					workweekEventID:$event.attr('workweekeventid'),
					name:$input.val()
				};
				if(isNew){
					args.start_time = time;
					args.duration = 15;
					args.weekday = day;
				}
				Ajax.run({
					method:"workweekService.saveWorkweekEvent",
					args:args,
					onsuccess:function(data){
						$oldEvent.attr('workweekeventid',data);
						Workweek.loadEvent(data);
					}
				});
			}
		});
		
		// assign key listen for input
		$input.bind('keydown',function(e){
			if(e.keyCode == 27){ // esc
				$cancel.click();
			}
			if(e.keyCode == 13){ // enter
				$save.click();
			}
		});
		$event.append($cancel).append($input).append($save);
		// focus on the input and populate
		$input.val($event.attr('name'));
		$input.select();
	},
	getHover:function(x,y){
		var scrollX = $(window).scrollLeft();
		var scrollY = $(window).scrollTop();
		var hoverX = x + 80 - scrollX;
		var hoverY = y - scrollY + 6;
		var elements = document.elementFromPoint(hoverX,hoverY);
		var $hover = $(elements);
		if($hover.hasClass('workweek-event-name') || $hover.hasClass('edit-event-name')){
			var $event = $hover.parent();
			if($hover.hasClass('edit-event-name')){
				$event = $event.parent();
			}
			$event.hide();
			elements = document.elementFromPoint(hoverX,hoverY);
			$event.show();
			$hover = $(elements);
		}
		
		if($hover.hasClass('timeblock-time-text') || $hover.hasClass('ampmText')){
			$hover = $hover.closest('.timeblock');
		}
		// v TESTING CODE v
		if($hover.length > 0 && false){
			var $testBit = $('<div class="testBit"></div>');
			$testBit.css({
				position:'absolute',
				backgroundColor:"red",
				borderRadius:'5px',
				width:'3px',
				height:'3px'
			});
			$testBit.css({left:(hoverX+1+scrollX)+"px",top:(hoverY+1+scrollY)+"px"});
			$('body').append($testBit);
			$testBit.fadeOut(500,function(){$(this).remove();});
		}
		// ^ TESTING CODE ^
		return $hover;
	},
	highlightHoverEligible:function($hover,size){
		$('.eligible').removeClass('eligible');
		$('.eligible-time').removeClass('eligible-time');
		var capacity = $hover.attr('capacity');
		if(capacity >= size){
			// loop next X=size times and add "eligible"
			$hover.addClass('eligible').addClass('eligible-time');
			for(var i = 0; i < size-1; i++){
				$hover = $hover.next();
				$hover.addClass('eligible');
			}
			$hover.next().addClass('eligible-time');
		}
	},
	showAddWorkweekEvents:function(that){
		var $this = $(that);
		var $add = $('.add_workweek');
		$add.find('.form-input-value input:hidden,.form-input-value select:hidden,.form-input-value .form-input-value-list:hidden').each(function(){
			$(this).show();
		});
		$add.find('span.form-input-input-value').each(function(){
			$(this).hide();
		});
		$this.fadeOut();
		$add.fadeIn(function(){
			$add.find('input[name=name]').focus();
		});
	},
	cancelAddAction:function(that){
		var $this = $(that);
		var $add = $('.add_workweek');
		$add.fadeOut();
		$('.add_workweek_button').fadeIn();
	},
	copyUnscheduledEvent:function(that,e){
		var $this = $(that);
		$this.css({opacity:".5"});
		var $clone = $this.clone();
		// record original positions
		Workweek.cloneX = $this.offset().left;
		Workweek.cloneY = $this.offset().top;
		Workweek.mouseX = e.pageX;
		Workweek.mouseY = e.pageY;
		// size the clone according to duration
		var duration = +$this.attr('duration');
		var size = duration / 15;
		var height = $this.height() * size;
		// find the clone's category
		var category = $this.attr('class');
		var index = category.indexOf('we-cat');
		category = category.charAt(index+6);
		$clone.addClass('we-cat'+category);
		// setup the clone
		$clone.attr('id',that.id + "_clone");
		$clone.addClass('clone');
		$clone.attr('size',size);
		$clone.css({
			opacity:.7,
			minHeight:height+"px",
			width:$this.width()+"px",
			display:"inlineBlock",
			position:"absolute",
			top:Workweek.cloneY+"px",
			left:Workweek.cloneX+"px",
			zIndex:"100000"
		});
		// record the dragged event data
		var day = $this.closest('.weekday').attr('day');
		WEvent.set(
			$clone.attr('id').substring(0,32),
			$clone.attr('name'),
			duration,
			day,
			'',
			category
		);
		// dim all the other days
		$('.weekday').not('[day='+day+']').css({opacity:.5});
		// set clone
		Workweek.$clone = $clone;
		$('body').prepend(Workweek.$clone);
	},
	destroyClones:function(){
		// re-opacity the original event
		if(Workweek.$clone.length){
			var id = Workweek.$clone.attr('id').substring(0,32);
			$('#'+id).css('opacity','1');
		}
		Workweek.$clone.remove();
		Workweek.$clone = $();
		$('.eligible').removeClass('eligible');
	},
	calculateCapacity:function(day){
		// get all the timeblocks
		var $blocks = $('[day='+day+']').find('.timeblock').not('.unscheduled');
		// loop forward and mark event cells with workweek-event
		$blocks.removeClass('workweek-event');
		var $scheduled = $blocks.find('.scheduled-event');
		$scheduled.each(function(){
			var $this = $(this);
			var $timeblock = $this.closest('.timeblock');
			var duration = +$this.attr('duration');
			var steps = (duration / 15)-1;
			var $next = $timeblock.next();
			$timeblock.addClass('workweek-event');
			for(var i = 0; i < steps; i++){
				if($next.length > 0){
					$next.addClass('workweek-event');
				}
				$next = $next.next();
			}
		});
		// loop backwards
		var capacity = 0;
		for(var i = $blocks.length-1; i >= 0; i--){
			var $block = $($blocks[i]);
			capacity++;
			if($block.hasClass('workweek-event')){
				capacity = 0;
			}
			$block.attr('capacity',capacity);
		}
	},
	scheduleUnscheduledEvent:function(skipTest){
		var skipTest = skipTest || false;
		var event = WEvent.get();
		if(event.id == ""){
			return;
		}
		var name = Workweek.$clone.attr('name');
		$('.eligible').addClass('workweek-event');
		var $firstEligible = $('.eligible:first');
		var day = +$firstEligible.closest('.weekday[day]').attr('day');
		var hour = $firstEligible.attr('hour');
		var quarter = $firstEligible.attr('quarter');
		// inject the eventHTML
		Workweek.injectEvent(event.id,event.name,event.duration,hour,quarter,day);
		// recalculate capacity
		Workweek.calculateCapacity(day);
		// hide the unscheduled
		$('#'+event.id).remove();
		// see if unscheduled header needs to be hidden
		Workweek.evaluateUnscheduledHeaders();
		// save to database
		var minute = (+quarter - 1) * 15;
		var time = Workweek.getTimeString(hour,minute);
		Workweek.saveEventTime(event.id,event.day,event.duration,time);
		
		// NEW IDEA !! look for similar events to schedule
		if(skipTest){return;}
		var $unscheduled = $('.unscheduled.we-cat'+event.category+'[duration='+event.duration+']').not('.clone');
		$unscheduled = $unscheduled.filter(function(){
			return $(this).attr('name') == event.name;
		});
		// filter again for scheduleability
		$unscheduled = $unscheduled.filter(function(){
			var $this = $(this);
			//get the day
			var $day = $this.closest('[day]');
			// get the timeblock
			var $timeblock = $day.find('.timeblock[hour='+hour+'][quarter='+quarter+']');
			return +$timeblock.attr('capacity') >= (event.duration / 15);
		});
		// humanize hour and minute for confirm dialog
		var humanMinute = minute;
		if(minute < 10){
			humanMinute = '0'+minute;
		}
		var ampm = ' AM';
		var humanHour = hour;
		if(hour > 12){		humanHour = hour - 12;	ampm = ' PM'	}
		if(hour == 0){		humanHour = 12;						}
		if($unscheduled.length > 0 && confirm('Schedule other "'+event.name+'" for '+humanHour+':'+humanMinute+ampm+'?')){
			var timeout = 0;
			$unscheduled.each(function(){
				var $this = $(this);
				setTimeout(function(){
					// remove eligible
					$(".eligible").removeClass('eligible');
					var $day = $this.closest('[day]');
					var day = $day.attr('day');
					// setup WEvent
					WEvent.set($this.attr('id'),event.name,event.duration,day,'',event.category);
					// setup eligible events
					var $timeblock = $day.find('.timeblock[hour='+hour+'][quarter='+quarter+']');
					$timeblock.addClass('eligible');
					for(var i = 0; i < event.duration / 15; i++){
						$timeblock = $timeblock.next();
						$timeblock.addClass('eligible');
					}
					// call save
					Workweek.scheduleUnscheduledEvent(true);
				},timeout);
				timeout += 500;
			});
		}
	},
	evaluateUnscheduledHeaders:function(){
		for(var day = 0; day < 7; day++){
			var $day = $('.weekday[day='+day+']');
			var length = $day.find('.workweek-event.unscheduled:visible').length;
			if(length == 0){
				$day.find('.unscheduled-title').hide();
			} else {
				var text = length + ' unscheduled event';
				if(length > 0){
					text += "s";
				}
				$day.find('.unscheduled-title').show().text(text);
			}
		}
	},
	getTimeString:function(hour,minute){
		if(hour < 10) {
			hour = '0'+hour;
		}
		if(minute < 10){
			minute = '0'+minute;
		}
		return '01/01/2014 ' + hour + ':' + minute + ':00';
	},
	quarterToMinute:function(quarter){
		var quarter = +quarter;
		return (quarter - 1) * 15;
	},
	saveEventTime:function(id,day,duration,time){
		$('.eligible-time').removeClass('eligible-time');
		$('.eligible').removeClass('eligible');
		Ajax.run({
			method:"workweekService.saveWorkweekEvent",
			args:{
				workweekEventID:id,
				weekday:day,
				duration:duration,
				start_time:time
			},
			onsuccess:function(){
				Workweek.loadEvent(id);
			}
		});
	},
	getEventHTML:function(id,name,duration,category){
		// name should only be as long as (duration / 15) * 23
		var fullName = name;
		var maxLength = (duration / 15) * 23;
		if(name.length > maxLength){
			name = name.substring(0,maxLength)+'..';
		}
		// begin event building
		var $event = $('<div class="scheduled-event we-cat'+category+'" workweekeventid="'+id+'" duration="'+duration+'" name="'+fullName+'"><span class="workweek-event-name"><div class="workweek-category-picker we-cat'+category+'b"></div><a class="edit-event-name">'+name+'</a></span></div>');
		$event.css({
			height:(duration-1)+"px"
		});
		// append the duration
		var $duration = ('<div class="scheduled-event-duration">'+Workweek.humanizeDuration(duration)+'</div>');
		// append the resize bar
		var $resize = $('<div class="drag-resize"><div class="drag-resize-up"></div><div class="drag-resize-down"></div></div>');
		// append the delete button
		var $delete = $('<i class="fa fa-times delete-workweek" onclick="Workweek.deleteEvent(\''+id+'\')"></i>')
		$event.prepend($duration);
		$event.prepend($resize);
		$event.prepend($delete);
		return $event;
	},
	injectEvent:function(id,name,duration,hour,quarter,day,category,goal_id,goal_name){
		var goal_id = goal_id || "";
		var goal_name = goal_name || "";
		// never allow 2 events of same id to exist
		$('.scheduled-event[workweekeventid='+id+']').remove();
		var $event = Workweek.getEventHTML(id,name,duration,category);
		// find where to inject
		var $day = $('.weekday[day='+day+']');
		var $timeblock = $day.find('.timeblock[hour='+hour+'][quarter='+quarter+']');
		// if timeblock isn't there, look for existing unscheduled
		if($timeblock.length == 0){
			$('#'+id+'.unscheduled').show();
		} else {
			$timeblock.prepend($event);
		}
		if(goal_id != ""){
			var goal_text = "Goal:\n"+goal_name;
			// append goal target if exists
			var $goal = $('<i class="fa fa-crosshairs workweek-goal" title="'+goal_text+'"></i>');
			$event.append($goal);
		}

		// calculate capacity
		Workweek.calculateCapacity(day);
	},
	humanizeDuration:function(duration){
		var totalMinutes = +duration;
		var hours = 0;
		var minutes = totalMinutes % 60;
		totalMinutes -= minutes;
		if(totalMinutes > 0){
			hours = totalMinutes / 60;
		}
		var result = "";
		if(+duration == 60){
			result = "1 hr";
		} else if(+duration < 60 || +duration == 90){
			result = duration + ' mins';
		} else {
			if(minutes == 0){
				minutes = '00';
			}
			result = hours + ':' + minutes + " hr";
			if(+duration > 60){
				result += "s";
			}
		}
		result = result.replace(':00','');
		return result;
	},
	loadEvent:function(id){
		// find the scheduled event
		var $event = $('.scheduled-event[workweekeventid='+id+']');
		// set opacity to .7 (loading)
		$event.addClass('saving');
		setTimeout(function(){
			Ajax.run({
				method:"workweekService.getWorkweekEvents",
				args:{workweekEventID:id},
				onsuccess:function(data){
					Workweek.injectEvent(
						Query.column(data,'id'), //id
						Query.column(data,'name'), // name
						Query.column(data,'duration'), // duration
						Query.column(data,'hour'), // hour
						(+Query.column(data,'minute')/15)+1, // quarter
						Query.column(data,'weekday'), // day
						Query.column(data,'category'), // category
						Query.column(data,'goal_id'),
						Query.column(data,'goal_name')
					);
					$event.css({opacity:"1"});
					$(document).trigger('secretary.reload');
				}
			});
		},500);
	},
	expanding:false,
	toggleUnscheduled:function(day){
		var limit = 0;
		var $days = $('.weekday[day]');
		var $unscheduled = $days.find('.unscheduled-title');
		if(Workweek.expanding){
			return;
		} else {
			Workweek.expanding = true;
		}
		if($unscheduled.hasClass('collapsed')){
			$unscheduled.removeClass('collapsed');
			$days.find('.unscheduled').each(function(){
				var $this = $(this);
				setTimeout(
					function(){
						$this.show();
					}
				,limit);
				limit+=55;
			});
		} else {
			$unscheduled.addClass('collapsed');
			$days.find('.unscheduled').each(function(){
				var $this = $(this);
				setTimeout(
					function(){
						$this.hide();
					}
				,limit);
				limit+=55;
			});
		}
		setTimeout(function(){
			Workweek.expanding = false;
		},limit);
	},
	validateSaveWorkweekEvents:function(that){
		var $form = $(that);
		if($form.find('[name=days]:checked').length == 0){
			var $label = $form.find('[name=days]:first').closest('.form-input').find('.form-input-label');
			var color = $label.css('color');
			$label.css({color:"red",fontWeight:"bold"});
			setTimeout(function(){	
				$label.css({color:color,fontWeight:"normal"});
			},1500);
			return false;
		} else {
			return true;
		}
	},
	showAdd:function(that){
		$(that).fadeOut();
		$('#add_form').fadeIn(function(){
			$('#add_form').find('input[name=name]').focus();		
		});
	},
	hideAdd:function(){
		$('#add_events').fadeIn();
		$('#add_form').slideUp();
	},
	deleteEvent:function(id){
		if(confirm('Remove this action?')){
			var $event = $('[workweekeventid='+id+'],#'+id);
			var day = $event.closest('[day]').attr('day');
			$event.fadeOut();
			Ajax.run({
				method:"workweekService.deleteWorkweekEvent",
				args:{workweekEventID:id},
				onsuccess:function(data){
					$event.remove();
					Workweek.calculateCapacity(day);
					Workweek.evaluateUnscheduledHeaders();
				},
				onfail:function(){
					$event.fadeIn();
				}
			});
		}
	},
	showCreateEvent:function(that){
		var $timeblock = $(that).closest('.timeblock');
		var $event = Workweek.getEventHTML('','',15,0);
		$timeblock.append($event);
		Workweek.renderEditControls($event,true);
	},
	changeFirstDay:function(first_day){
		for(var i = 0; i < first_day; i++){
			var first = $('div[day]:First');
			$('div[day]:last').after(first);
		}
	}
};	